import React, {Component} from 'react';
import {connect} from 'react-redux'
import logo from "../../../static/logo.png";
import {Menu,Layout} from "antd";
import leftMenuData from "../../../config/menu-config";
import {Link,withRouter} from "react-router-dom";
import "./left_nav.less"
import {createSaveMenuTitleAction} from '../../../redux/actions/menu_action.js'

const {Sider} = Layout;
const { SubMenu } = Menu;

class Left_nav extends Component {
  render() {
    return <Sider className="sider">
      <header className="left-nav-header">
        <img src={logo} alt="logo"/>
        <div className="title">商品管理后台</div>
      </header>
      <div>
        <Menu
          selectedKeys={this.props.location.pathname.split('/').reverse()}
          defaultOpenKeys={this.props.location.pathname.split('/').splice(2)}
          mode="inline"
          theme="dark"
        >
          {/*创建左侧菜单*/}
          {this.createMenu(leftMenuData)}
        </Menu>
      </div>
    </Sider>
  }
  
  // 判断用户可以查看的选项权限
  hasRole = (item) => {
    // 用户name
    let userName = this.props.userInfo.user.username
    // 用户权限
    let menus = [...this.props.userInfo.user.role.menus]
  
    // 处理权限列表数组
    menus.forEach((item,i) => {
      if (item === '/products') {
        menus[i] = '/prod_about'
      }
    })
   
    if (userName === 'admin') {  // 如果是admin超级管理员，默认return true，拥有全部权限
      return true
    } else {  // 如果不是admin超级管理员
      if (item.children) {  // 如果有children
        let flag = false
        // 如果这个有children的选项子元素在权限列表数组中，改变flag=true
        item.children.forEach(itemChildren => {
          let itemChild = '/'+itemChildren.key
          return flag = menus.includes(itemChild)
        })
        return flag
      } else {  // 如果没有children
        let menu = '/' +item.key
        return menus.includes(menu)
      }
    }
  }
  
  // 创建左侧菜单选项
  createMenu = (leftMenuData) => {
    return leftMenuData.map(item => {
      if (item.children ){    // 如果有children
        if (this.hasRole(item)){  // 判断这个选项是否在权限列表数组中
          // 渲染此父选项
          return <SubMenu key={item.key} icon={item.icon} title={item.title}>
            {/* 通过回调函数，遍历子元素*/}
            {this.createMenu(item.children)}
          </SubMenu>
        }
      } else {   // 如果没有children
        // 判断这个选项是否在权限列表数组中
        if (this.hasRole(item)){
          // 渲染此选项
          return <Menu.Item key={item.key} icon={item.icon} onClick={this.props.saveMenuTitle.bind(this, item.title)}>
            <Link to={item.path}>
              {item.title}
            </Link>
          </Menu.Item>
        }
      }
    })
  }
}

export default withRouter(connect(
  state => ({userInfo:state.userInfo}),
  {
    saveMenuTitle: createSaveMenuTitleAction
  }
)(Left_nav));
